// 消息订阅发布
const pubSub = {
  id: 1,
  callbacks: {
    // pay: {
    //   token_1: cb1,
    // },
  },
};
/**订阅 */
pubSub.subscribe = function (chanel, cb) {
  let token = "token_" + this.id++;
  if (this.callbacks[chanel]) {
    this.callbacks[chanel][token] = cb;
  }
  // 初始化
  else {
    this.callbacks[chanel] = {
      [token]: cb,
    };
  }
  return token;
};

/**发布消息 */
pubSub.publish = function (chanel, data) {
  if (this.callbacks[chanel]) {
    Object.values(this.callbacks[chanel]).forEach((cb) => {
      cb(data);
    });
  }
};

// 取消订阅
pubSub.unsubscribe = function (flag) {
  // 如果flag为undefined清空所有
  if (flag === undefined) {
    this.callbacks = {};
  } else if (typeof flag === "string") {
    // 订阅id
    if (flag.indexOf("token_") === 0) {
      let cbObj = Object.values(this.callbacks).find((obj) =>
        obj.hasOwnProperty(flag)
      );
      if (cbObj) {
        delete cbObj[flag];
      }
    }
    // 频道名称
    else {
      delete this.callbacks[flag];
    }
  }
};

// 订阅一个频道
let pid = pubSub.subscribe("pay", (data) => {
  console.log("商家接到了订单", data);
});
let pid2 = pubSub.subscribe("pay", (data) => {
  console.log("骑手接到订单", data);
});
pubSub.subscribe("cancel", (data) => {
  console.log("商家接到取消的请求", data);
});
pubSub.publish("pay", {
  title: "鱼香肉丝盖饭",
  price: 20,
  pos: "三年二班",
});
console.log(pid, pid2);
pubSub.unsubscribe(pid);
console.log(pubSub);
